const Service = require("egg").Service;

class FileService extends Service {
  async folder_list() {
    const result = await this.app.mysql.select("folder");
    return result;
  }
  async file_list(child_id) {
    // const result = await this.app.mysql.select("file", {
    //   where: { folder_id: child_id }
    // })
    const result = await this.app.mysql.query(
      `select * from file where folder_id in (${child_id})`
    );
    return result;
  }

  async uplode_file(list = []) {
    let md5_result = [];

    //  md5不同
    const judgment = (child, item) => {};
    const file_update = async (md5_result) => {
      if (list.length === 0) return;
      md5_result.map((item) => {
        list = list.filter((child) => item.file_md5 && child.name === item.name);
      });

      const result = await this.app.mysql.beginTransactionScope(
        async (conn) => {
          if (list.length === 0) return { success: true };
          await conn.updateRows('file', list)
          return { success: true };
        }
      );
      return result;
    };
    const file_insert = async (md5_result) => {
      if (list.length === 0) return;
      md5_result.map((item) => {
        const option1 = child.file_md5 !== item.file_md5;
        const option2 =
          child.file_md5 === item.file_md5 && child.name === item.name;

        list = list.filter((child) => judgment(child, item));
      });
      const values = list.map(
        ({ folder_id, name, path, file_md5 }) =>
          `('${folder_id}', '${name}','${path}','${file_md5}')`
      );

      const result = await this.app.mysql.beginTransactionScope(
        async (conn) => {
          if (values.length === 0) return { success: true };
          await conn.query(
            `insert into file(folder_id, name, path, file_md5) values ${values};`
          );
          return { success: true };
        }
      );
      return result;
    };

    const remove_file = async (list = []) => {
      const md5_arr = list.map((item) => item.file_md5).join();
      md5_result = await this.app.mysql.query(
        `select file_md5, name from file where file_md5 in ('${md5_arr}');`
      );
    };
    // 去重
    await remove_file(list);
    return await file_insert(md5_result);
  }
  // 查找文件md5和name
  async get_name_by_md5(file_md5) {
    return await this.app.mysql.get('file', { file_md5 })
  }
  // 查找文件md5和name
  async get_md5_by_name(name) {
    return await this.app.mysql.get('file', { name })
  }
  async handle_update_file(list = []) {
    list = list.map(item=>{
      const { file,...rest} = item || {}
      return ({...rest})
    })
    if(list.length === 0) return false
    return await this.app.mysql.insert('file', list)
  }
  async handle_update_data(list = []) {
    return await this.app.mysql.update('file', list)
  }
}

module.exports = FileService;
